package com.training.food.controller;

import com.training.food.Domain.Confirm;
import com.training.food.Domain.HisOrder;
import com.training.food.Domain.Release;
import com.training.food.pojo.User;
import com.training.food.service.*;
import com.training.food.util.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@RestController
public class ReleaseOrderController {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    ConfirmService confirmService;

    //接收订单时修改
    @PostMapping("/food/buy/confirmOrder")
    public CommonResult confirmOrder(HttpServletRequest request, @RequestBody Confirm confirm){
        if(confirm.getTz()==null||confirm.getTz().isEmpty()){
            return CommonResult.success("完成订单");
        }
        String token= (String) request.getAttribute("user");
        Object obj=redisTemplate.opsForValue().get(token);
        User user=(User)obj;
        char power=user.getPower();
        System.out.println(confirm.toString()+"     "+power);
        if(confirmService.confirm(confirm,power)){
            return CommonResult.success("完成订单");
        }
        return CommonResult.failed("服务器原因，请稍后重试！");
    }

    //发布订单
    @PostMapping("/food/buy/release")
    public CommonResult release(HttpServletRequest request, @RequestBody Release release){
        if(release==null){
            return CommonResult.success("成功");
        }
        String token= (String) request.getAttribute("user");
        Object obj=redisTemplate.opsForValue().get(token);
        User user=(User)obj;
        //传入登陆用户的账户信息
        if(confirmService.addReleaseOrder(release,user)){
            return CommonResult.success("发布订单成功");
        }
        return CommonResult.failed("服务器原因失败！");
    }
    //    个人订单展示
    @PostMapping("/food/buy/order")
    public CommonResult allOrderShow(HttpServletRequest request,@RequestBody List<String> states){
        if(states.isEmpty()){
            return CommonResult.failed("未查询到有关历史订单！");
        }
        String token= (String) request.getAttribute("user");
        Object obj=redisTemplate.opsForValue().get(token);
        User user=(User)obj;
        System.out.println(states.toString());
        //获取历史订单
        List<HisOrder> res=confirmService.allOrderShow(user,states);
        if(res==null||res.isEmpty()){
            return CommonResult.failed("未查询到有关历史订单！");
        }
        else{
            return CommonResult.success(res);
        }
    }
}
